<template>
    <div class="entity-query">
        <h3>Entity空间数据查询</h3>
        <div class="query-info">
            <p><strong>说明：</strong>Entity空间数据查询功能</p>
            <p>1. 先创建可查询Entity 2. 启用Entity选取 3. 点击Entity查看信息</p>
        </div>
        <div class="query-controls">
            <button @click="createQueryableEntities" class="create-btn">创建可查询Entity</button>
            <button @click="enableEntityPicking" class="pick-btn">启用Entity选取</button>
            <button @click="disableEntityPicking" class="disable-btn">禁用Entity选取</button>
            <button @click="clearQueryEntities" class="clear-btn">清除所有Entity</button>
        </div>
        <div class="query-status">
            <p v-if="isPickingEnabled">Entity选取：已启用</p>
            <p v-else>Entity选取：已禁用</p>
            <p v-if="lastPickedEntity">最后选取：{{ lastPickedEntity }}</p>
            <p v-if="popupVisible">自定义弹窗：已显示</p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted, onUnmounted } from 'vue';
import { XbsjEarthUi } from '../../../../scripts/xbsjEarthUi';
import EntityManager from './entityManager';

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;
const isPickingEnabled = ref(false);
const lastPickedEntity = ref('');
const popupVisible = ref(false);
let handler: any = null;
let popupDiv: HTMLElement | null = null;
const entityManager = EntityManager.getInstance();

// 获取EarthUI中的Cesium原生Viewer实例
const getCesiumViewer = () => {
    const viewer = xbsjEarthUi.activeViewer?.innerViewer?.viewer;
    console.log('获取到的viewer:', viewer);
    console.log('viewer类型:', typeof viewer);
    console.log('viewer.infoBox:', (viewer as any)?.infoBox);
    console.log('viewer.selectionIndicator:', (viewer as any)?.selectionIndicator);
    return viewer;
};

// 绑定关闭按钮事件
const bindCloseButton = () => {
    const closeBtn = document.getElementById('closePopup');
    if (closeBtn) {
        // 移除之前的事件监听器
        closeBtn.replaceWith(closeBtn.cloneNode(true));
        const newCloseBtn = document.getElementById('closePopup');
        if (newCloseBtn) {
            newCloseBtn.addEventListener('click', () => {
                if (popupDiv) {
                    popupDiv.style.display = 'none';
                    popupVisible.value = false;
                }
            });
        }
    }
};

// 创建可查询的Entity
const createQueryableEntities = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        console.log('开始创建Entity，viewer:', viewer);
        console.log('viewer.entities:', viewer.entities);
        
        // 创建建筑Entity（带详细信息）
        const buildingEntity = viewer.entities.add({
            id: 'building-1',
            position: (window as any).Cesium.Cartesian3.fromDegrees(116.0, 40.0), // 北京
            name: '管理学院',
            box: {
                dimensions: new (window as any).Cesium.Cartesian3(200000.0, 150000.0, 300000.0),
                material: (window as any).Cesium.Color.BLUE.withAlpha(0.7),
                outline: true,
                outlineColor: (window as any).Cesium.Color.BLACK
            },
            description: `
                <div style="text-align: center;">
                    <img width="100%" src="./assets/common/images.png" alt="管理学院">
                    <p><strong>管理学院</strong></p>
                    <p>资源: <a style="color: WHITE" href="http://glxy.cumtb.edu.cn/">管理学院网站</a></p>
                    <p>位置: 经度 116.0°, 纬度 40.0°</p>
                    <p>类型: 教学建筑</p>
                </div>
            `
        });
        
        console.log('建筑Entity创建成功:', buildingEntity);

        // 创建圆形Entity
        const circleEntity = viewer.entities.add({
            id: 'circle-1',
            position: (window as any).Cesium.Cartesian3.fromDegrees(121.0, 31.0), // 上海
            name: '圆形区域',
            ellipse: {
                semiMinorAxis: 200000.0,
                semiMajorAxis: 200000.0,
                material: (window as any).Cesium.Color.GREEN.withAlpha(0.5),
                outline: true,
                outlineColor: (window as any).Cesium.Color.DARKGREEN
            },
            description: `
                <div style="text-align: center;">
                    <p><strong>圆形区域</strong></p>
                    <p>半径: 200km</p>
                    <p>用途: 保护区</p>
                </div>
            `
        });

        // 创建折线Entity
        const polylineEntity = viewer.entities.add({
            id: 'polyline-1',
            name: '路径线',
            polyline: {
                positions: (window as any).Cesium.Cartesian3.fromDegreesArray([
                    113.0, 23.0, // 广州
                    115.0, 25.0,
                    117.0, 27.0,
                    119.0, 29.0,
                    121.0, 31.0  // 上海
                ]),
                width: 8,
                material: (window as any).Cesium.Color.ORANGE,
                clampToGround: true
            },
            description: `
                <div style="text-align: center;">
                    <p><strong>路径线</strong></p>
                    <p>长度: 约 800km</p>
                    <p>类型: 交通路线</p>
                </div>
            `
        });

        console.log('可查询Entity创建成功');
    } catch (error) {
        console.error('创建可查询Entity失败:', error);
    }
};

// 启用Entity选取
const enableEntityPicking = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer || isPickingEnabled.value) return;

    try {
        // 自动创建自定义弹窗
        createCustomPopup();
        
        handler = new (window as any).Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        
        handler.setInputAction((movement: any) => {
            console.log('点击位置:', movement.position);
            console.log('viewer.scene:', viewer.scene);
            console.log('viewer.scene.pick:', viewer.scene.pick);
            
            const pick = viewer.scene.pick(movement.position);
            console.log('选取结果:', pick);
            console.log('Cesium.defined(pick):', (window as any).Cesium.defined(pick));
            
            // 尝试其他选取方法
            const pickPosition = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
            console.log('pickPosition:', pickPosition);
            
            // 检查Entity集合
            console.log('当前Entity数量:', viewer.entities.values.length);
            console.log('Entity列表:', viewer.entities.values);
            
            if ((window as any).Cesium.defined(pick) && pick.id) {
                console.log('选取到Entity:', pick.id);
                // 显示弹窗
                if (popupDiv) {
                    const rect = viewer.scene.canvas.getBoundingClientRect();
                    const left = movement.position.x + rect.left + 10;
                    const top = movement.position.y + rect.top - 10;
                    
                    popupDiv.style.left = left + 'px';
                    popupDiv.style.top = top + 'px';
                    popupDiv.style.display = 'block';
                    popupVisible.value = true;

                    // 更新弹窗内容
                    const content = popupDiv.querySelector('div');
                    if (content) {
                        content.innerHTML = `
                            <h4 style="margin: 0 0 10px 0; color: #2196F3;">${pick.id.name || 'Entity信息'}</h4>
                            <p style="margin: 5px 0;"><strong>ID:</strong> ${pick.id.id}</p>
                            <p style="margin: 5px 0;"><strong>类型:</strong> ${pick.id.constructor.name}</p>
                            <p style="margin: 5px 0;">点击查看详细信息</p>
                            <button id="closePopup" style="
                                position: absolute;
                                top: 5px;
                                right: 10px;
                                background: none;
                                border: none;
                                font-size: 18px;
                                cursor: pointer;
                                color: #666;
                            ">×</button>
                        `;
                        
                        // 绑定关闭按钮事件
                        bindCloseButton();
                    }
                    console.log('弹窗已显示，位置:', left, top);
                } else {
                    console.log('弹窗元素不存在');
                }
                lastPickedEntity.value = `Entity: ${pick.id.name || pick.id.id}`;
            } else {
                console.log('未选取到Entity');
                // 隐藏弹窗
                if (popupDiv) {
                    popupDiv.style.display = 'none';
                    popupVisible.value = false;
                }
                lastPickedEntity.value = '未选取到Entity';
            }
        }, (window as any).Cesium.ScreenSpaceEventType.LEFT_CLICK);

        isPickingEnabled.value = true;
        console.log('Entity选取模式已启用，自定义弹窗已创建');
    } catch (error) {
        console.error('启用Entity选取失败:', error);
    }
};

// 禁用Entity选取
const disableEntityPicking = () => {
    if (handler) {
        handler.destroy();
        handler = null;
    }
    isPickingEnabled.value = false;
    lastPickedEntity.value = '';
    console.log('Entity选取模式已禁用');
};

// 创建自定义弹窗
const createCustomPopup = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        // 尝试禁用默认的Infobox和选择指示器（如果可用）
        console.log('检查viewer.infoBox:', viewer.infoBox);
        console.log('检查viewer.selectionIndicator:', viewer.selectionIndicator);
        
        if (viewer.infoBox && viewer.infoBox.enabled !== undefined) {
            viewer.infoBox.enabled = false;
            console.log('已禁用默认Infobox');
        } else {
            console.log('Infobox不可用，将使用自定义弹窗');
        }
        
        if (viewer.selectionIndicator && viewer.selectionIndicator.enabled !== undefined) {
            viewer.selectionIndicator.enabled = false;
            console.log('已禁用选择指示器');
        } else {
            console.log('选择指示器不可用，将使用自定义弹窗');
        }

        // 创建自定义弹窗HTML
        if (!popupDiv) {
            popupDiv = document.createElement('div');
            popupDiv.id = 'customPopup';
            popupDiv.style.cssText = `
                position: absolute;
                background: white;
                border: 2px solid #2196F3;
                border-radius: 8px;
                padding: 15px;
                box-shadow: 0 4px 8px rgba(0,0,0,0.3);
                z-index: 1000;
                max-width: 300px;
                display: none;
            `;
            popupDiv.innerHTML = `
                <div style="text-align: center;">
                    <h4 style="margin: 0 0 10px 0; color: #2196F3;">空间信息查询</h4>
                    <p style="margin: 5px 0;">点击地图上的Entity查看详细信息</p>
                    <button id="closePopup" style="
                        position: absolute;
                        top: 5px;
                        right: 10px;
                        background: none;
                        border: none;
                        font-size: 18px;
                        cursor: pointer;
                        color: #666;
                    ">×</button>
                </div>
            `;
            document.body.appendChild(popupDiv);

            // 添加关闭按钮事件
            const closeBtn = document.getElementById('closePopup');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    popupDiv!.style.display = 'none';
                    popupVisible.value = false;
                });
            }
        }

        // 设置Entity点击事件
        if (!handler) {
            handler = new (window as any).Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        }

        handler.setInputAction((movement: any) => {
            console.log('点击位置:', movement.position);
            console.log('viewer.scene:', viewer.scene);
            console.log('viewer.scene.pick:', viewer.scene.pick);
            
            const pick = viewer.scene.pick(movement.position);
            console.log('选取结果:', pick);
            console.log('Cesium.defined(pick):', (window as any).Cesium.defined(pick));
            
            // 尝试其他选取方法
            const pickPosition = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
            console.log('pickPosition:', pickPosition);
            
            // 检查Entity集合
            console.log('当前Entity数量:', viewer.entities.values.length);
            console.log('Entity列表:', viewer.entities.values);
            
            if ((window as any).Cesium.defined(pick) && pick.id) {
                console.log('选取到Entity:', pick.id);
                // 显示弹窗
                if (popupDiv) {
                    const rect = viewer.scene.canvas.getBoundingClientRect();
                    const left = movement.position.x + rect.left + 10;
                    const top = movement.position.y + rect.top - 10;
                    
                    popupDiv.style.left = left + 'px';
                    popupDiv.style.top = top + 'px';
                    popupDiv.style.display = 'block';
                    popupVisible.value = true;

                    // 更新弹窗内容
                    const content = popupDiv.querySelector('div');
                    if (content) {
                        content.innerHTML = `
                            <h4 style="margin: 0 0 10px 0; color: #2196F3;">${pick.id.name || 'Entity信息'}</h4>
                            <p style="margin: 5px 0;"><strong>ID:</strong> ${pick.id.id}</p>
                            <p style="margin: 5px 0;"><strong>类型:</strong> ${pick.id.constructor.name}</p>
                            <p style="margin: 5px 0;">点击查看详细信息</p>
                            <button id="closePopup" style="
                                position: absolute;
                                top: 5px;
                                right: 10px;
                                background: none;
                                border: none;
                                font-size: 18px;
                                cursor: pointer;
                                color: #666;
                            ">×</button>
                        `;
                        
                        // 绑定关闭按钮事件
                        bindCloseButton();
                    }
                    console.log('弹窗已显示，位置:', left, top);
                } else {
                    console.log('弹窗元素不存在');
                }
                lastPickedEntity.value = `Entity: ${pick.id.name || pick.id.id}`;
            } else {
                console.log('未选取到Entity');
                // 隐藏弹窗
                if (popupDiv) {
                    popupDiv.style.display = 'none';
                    popupVisible.value = false;
                }
                lastPickedEntity.value = '未选取到Entity';
            }
        }, (window as any).Cesium.ScreenSpaceEventType.LEFT_CLICK);

        console.log('自定义弹窗创建成功');
    } catch (error) {
        console.error('创建自定义弹窗失败:', error);
    }
};

// 清除查询Entity
const clearQueryEntities = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        // 只清除全局管理器中的Entity
        entityManager.clearAllEntities(viewer);
        lastPickedEntity.value = '';
        popupVisible.value = false;
        if (popupDiv) {
            popupDiv.style.display = 'none';
        }
        
        // 恢复默认的Infobox和选择指示器（添加安全检查）
        if (viewer.infoBox && viewer.infoBox.enabled !== undefined) {
            viewer.infoBox.enabled = true;
        }
        if (viewer.selectionIndicator && viewer.selectionIndicator.enabled !== undefined) {
            viewer.selectionIndicator.enabled = true;
        }
        
        console.log('查询Entity已清除');
    } catch (error) {
        console.error('清除查询Entity失败:', error);
    }
};

onMounted(() => {
    console.log('Entity查询组件已加载');
});

onUnmounted(() => {
    // 组件卸载时清理
    disableEntityPicking();
    if (popupDiv) {
        document.body.removeChild(popupDiv);
        popupDiv = null;
    }
});
</script>

<style scoped>
.entity-query {
    width: 280px;
    box-sizing: border-box;
    padding: 10px;
}

.query-info {
    box-sizing: border-box;
    font-size: 14px;
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    margin-bottom: 15px;
}

.query-controls {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
}

.create-btn, .pick-btn, .disable-btn, .clear-btn {
    margin-bottom: 8px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.create-btn {
    background-color: #2196F3;
    color: white;
}

.create-btn:hover {
    background-color: #1976D2;
}

.pick-btn {
    background-color: #4CAF50;
    color: white;
}

.pick-btn:hover {
    background-color: #45a049;
}

.disable-btn {
    background-color: #FF9800;
    color: white;
}

.disable-btn:hover {
    background-color: #F57C00;
}

.clear-btn {
    background-color: #f44336;
    color: white;
}

.clear-btn:hover {
    background-color: #d32f2f;
}

.query-status {
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    border-left: 4px solid #2196F3;
    color: #2196F3;
    font-weight: bold;
}
</style>
